﻿#include "myapp.h"
#include <sys/stat.h>
#include <sys/types.h>

// #include <unistd.h>
#include "myhelper.h"
#include <fcntl.h>
#include <iostream>
using namespace std;

// #include "mywebsocket.h"
QList<WebSocketParam> myApp::g_websocketlist;
QString myApp::AppPath = "";
int     myApp::DeskWidth = 1920;
int     myApp::DeskHeight = 1080;
QRect   myApp::Desk = QRect(0, 0, 1920, 1080);
float   myApp::Width_Scale = 1;
float   myApp::Height_Scale = 1;
int     myApp::LogFileCount = 30;       /* 默认30天 */
QString myApp::CurrentLogFileName = ""; /* 当前日志文件名 */
QString myApp::DevType = "HT_CN";
int     myApp::software_ver1 = 0;
int     myApp::software_ver2 = 1;
QString myApp::httpserver = "192.168.2.250"; // http IP地址
int     myApp::httpport = 8100;              // http 端口号
int     myApp::role = 0;                     // 角色
QString websocketAddr = "ws://192.168.110.229:8108";

QString  myApp::current_chnnid = "";
QString  myApp::current_devId = "";



QString myApp::ServerIP = "10.207.116.21";    //服务器ip
QString myApp::DatabaseIP = "10.207.116.21";  // 数据库ip
QString myApp::DatabaseName = "drilldb";      // 数据库名
QString myApp::DatabaseUserName = "root";     // 数据库账号
QString myApp::DatabasePassword = "ht123456"; // 数据库密码

QString myApp::Current_user = "admin";
QString myApp::Current_user_role = "管理员";

QString myApp::localip = "192.168.110.162";

QString myApp::AiCam_H = "AI高速相机";
QString myApp::AiCam_L = "AI中低速相机";
QString myApp::Ai_ARM = "分析装置";
QString myApp::Ai_GPU = "GPU服务器";
QString myApp::Ai_FACE = "人脸服务器";
QString myApp::Ai_DZFT = "电子封条分析装置";

QStringList myApp::ips;
#ifdef __unix__
    QString myApp::FILEPATH = "/ftpserver/";
#else // ifdef __unix__
    // QString myApp::FILEPATH = "D://ptulog//";
    QString myApp::FILEPATH = "D://ptulog//";
#endif // ifdef __unix__
int myApp::rectime = 10;



void myApp::init_param()
{
    QString fileName = myApp::AppPath + "config.ini";

    qDebug() << "myApp::init_param:" << fileName;

    // 如果配置文件不存在,则以初始值继续运行
    if (!FileHelper::FileExists(fileName))
    {
        WriteConfig();
        return;
    }
    qDebug() << "Read All Config Data!";
    ReadConfig();
}

// 读取配置文件
void myApp::ReadConfig()
{
    QString fileName = myApp::AppPath + "config.ini";

    qDebug() << "ReadConfig:filename=" << fileName;

    // 如果配置文件不存在,则以初始值继续运行
    if (!FileHelper::FileExists(fileName))
    {
        return;
    }
    QSettings* set = new QSettings(fileName, QSettings::IniFormat);
    set->setIniCodec("UTF-8");
    set->beginGroup("SYSTEM");
    myApp::AiCam_H = set->value("AiCam_H").toString();
    myApp::AiCam_L = set->value("AiCam_L").toString();
    myApp::Ai_ARM = set->value("Ai_ARM").toString();
    myApp::Ai_GPU = set->value("Ai_GPU").toString();
    myApp::Ai_FACE = set->value("Ai_FACE").toString();
    myApp::Ai_DZFT = set->value("Ai_DZFT").toString();
    set->endGroup();
}

// 写入配置文件
void myApp::WriteConfig()
{
    QString fileName = myApp::AppPath + "config.ini";

    // 如果配置文件不存在,则以初始值继续运行
    //    if(!myHelper::FileIsExist(fileName)) {
    //        return;
    //    }
    QSettings* set = new QSettings(fileName, QSettings::IniFormat);
    set->setIniCodec("UTF-8");
    set->beginGroup("SYSTEM");
    set->setValue("AiCam_H", myApp::AiCam_H);
    set->setValue("AiCam_L", myApp::AiCam_L);
    set->setValue("Ai_ARM", myApp::Ai_ARM);
    set->setValue("Ai_GPU", myApp::Ai_GPU);
    set->setValue("Ai_FACE", myApp::Ai_FACE);
    set->setValue("Ai_DZFT", myApp::Ai_DZFT);
    set->endGroup();
}

// 此函数里不能打印日志信息
void ManageLogFile()
{
    int i = 0;
    QString str = myApp::AppPath + "//ptulog//";
    QDir    dir(str);
    if (dir.exists() == false) /* 不存在 */
    {
        dir.mkdir(str);
    }
    QString tmpstr;
    QStringList logfilelist;

    logfilelist.clear();
    foreach(QFileInfo mfi, dir.entryInfoList())
    {
        if (mfi.isFile())
        {
            tmpstr = mfi.fileName();

            if (tmpstr.count() > 4)
            {
                if (tmpstr.right(4) == ".txt")
                {
                    logfilelist.append(mfi.fileName());
                }
            }
        }
    }
    logfilelist.sort();

    if (logfilelist.count() > myApp::LogFileCount)
    {
        for (i = 0; i < (logfilelist.count() - myApp::LogFileCount); i++)
        {
            QFile::remove(str + "/" + logfilelist.at(i));
        }
    }
}

// 此函数里不能打印日志信息
void outputMessage(QtMsgType                 type,
                   const QMessageLogContext& context,
                   const QString&            msg)
{
    static QMutex mutex;

    mutex.lock();
    QString text;

    switch (type)
    {
        case QtDebugMsg:
            text = QString("Debug:");
            break;

        case QtWarningMsg:
            text = QString("Warning:");
            break;

        case QtCriticalMsg:
            text = QString("Critical:");
            break;

        case QtFatalMsg:
            text = QString("Fatal:");
    }
    QString context_info = QString("File:(%1) Line:(%2)").arg(QString(
                               context.file)).
                           arg(context.line);
    QString current_time = QTime::currentTime().toString("hh:mm:ss");

    // QString message = QString("[%1] %2 {%3
    // %4}").arg(current_time).arg(msg).arg(text).arg(context_info);
    QString message = QString("[%1] %2").arg(current_time).arg(msg);
    QString logfilename = QDate::currentDate().toString("yyyyMMdd") + ".txt";

    if (logfilename != myApp::CurrentLogFileName)
    {
        ManageLogFile();
        myApp::CurrentLogFileName = logfilename;
    }

//    QString str = myApp::FILEPATH;
    //QString str = myApp::AppPath + "log/";
    QFile   file(myApp::AppPath + "//ptulog//" + logfilename);

    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(&file);

    text_stream << message << "\r\n";
    cout << QString(message.constData()).toStdString() << endl;
    file.flush();
    file.close();
    mutex.unlock();
}

// 获取毫秒级时间戳
qint64 myApp::GetMSecsTimeStamp()
{
    QDateTime time = QDateTime::currentDateTime(); // 获取当前时间
    qint64    timeT = time.toMSecsSinceEpoch();    // 将当前时间转为毫秒级时间戳

    return timeT;
}

QString myApp::GetFileName(enum FILETYPE type, QString camid)
{
    QString filename = myApp::FILEPATH;
    QDir    dir(myApp::FILEPATH);

    if (dir.exists() == false) /* 不存在 */
        dir.mkdir(filename);

    if (type == FILETYPE_WAV)  // 录像文件
        filename = filename + "//audio";
    else if (type == FILETYPE_REC) filename = filename + "//record";
    else filename = filename + "//JPG";
    dir.setPath(filename);

    if (dir.exists() == false) /* 不存在 */
        dir.mkdir(filename);

    filename = filename + "//" + QDate::currentDate().toString("yyyyMMdd");
    dir.setPath(filename);

    if (dir.exists() == false) /* 不存在 */
        dir.mkdir(filename);

    switch (type)
    {
        case FILETYPE_REC:
            {
                filename = filename + QString("//%1_%2.mp4").arg(camid).arg(
                               QDateTime::currentDateTime().toString("yyyyMMddhhmmss"));
                break;
            }

        case FILETYPE_ALARM_JPG:
            {
                filename = filename + QString("//%1_alarm_%2_%3.jpg").arg(camid).arg(
                               QDateTime::currentDateTime().toString("yyyyMMddhhmmss")).arg(
                               qrand() % (1000));
                break;
            }

        case FILETYPE_SNAP_JPG:
            {
                filename = filename + QString("//%1_snap_%2_%3.jpg").arg(camid).arg(
                               QDateTime::currentDateTime().toString("yyyyMMddhhmmss")).arg(
                               qrand() % (1000));
                break;
            }

        case FILETYPE_WAV:
            {
                filename = filename + QString("//%1_%2.wav").arg(camid).arg(
                               QDateTime::currentDateTime().toString("yyyyMMddhhmmss"));
                break;
            }

        default:
            {
                filename = "";
                break;
            }
    }
    return filename;
}
